import React, { useEffect } from "react";
import { Button, Space, Dropdown, Modal, message, Input } from 'antd'
import { APP_STATUS, PLAYER_STATUS, PLAYER_MODE } from '@/common/constant'
import { useDispatch, useSelector } from "react-redux";
import { playerPlay } from '@/actions/index'
import { getPlayTab } from "@/ext/common/tab";
import { PLAY_MODE } from '@/types/player'
import { State } from '@/reducers'
import type { MenuProps } from 'antd';
import { player } from '@/runner/player'
import Ext, { isFirefox } from '@/common/web_extension'
import { askBg } from "@/ext/ipc";
import { startRecording, stopRecording, updateUI, saveEditingAsNew, saveEditingAsExisted } from '@/actions'
import { hasUnsavedMacro } from '@/recomputed';
import './index.less'

export default function PanelHeader() {

    const dispatch = useDispatch()
    const status = useSelector((state: State) => state.status)
    const mode = useSelector((state: State) => state.player.mode)
    const commands = useSelector((state: State) => state.editor.editing.commands);
    const macroId = useSelector((state: State) => state.editor.editing.meta.src?.id)
    const macroName = useSelector((state: State) => state.editor.editing.meta.src?.name)
    const playerStatus = useSelector((state: State) => state.player.status)
    const state = useSelector((state: State) => state)
    const hasUnsaved = hasUnsavedMacro(state)

    // 播放当前用例
    const playCurrentMacro = async (isStep: boolean) => {

        const fn = async () => {
            const tab: any = await getPlayTab()

            dispatch(playerPlay({
                macroId,
                title: macroName,
                extra: {
                    id: macroId,
                },
                mode: PLAY_MODE.STRAIGHT,
                playUrl: tab.url,
                playtabIndex: tab.index,
                playtabId: tab.id,
                startIndex: 0,
                startUrl: tab.url,
                resources: commands, // 执行的是展开后的所有命令
                postDelay: 1000,
                isStep,
                superFast: false,
                hasOnDownloadCmd: false,
            }))
        }

        if (hasUnsaved) {
            Modal.confirm({
                title: '是否保存',
                onOk() {
                    fn()
                }
            })
        } else {
            fn()
        }

    }

    const handleButtonClick = (e: React.MouseEvent<HTMLButtonElement>) => {
        playCurrentMacro(false)
    };

    const handleMenuClick: MenuProps['onClick'] = (e) => {
        let count = 1
        Modal.confirm({
            title: '设置循环次数',
            content: <Input placeholder="循环次数" defaultValue={count} onChange={(e) => {
                count = Number(e.target.value) || 0
            }} />
            ,
            onOk: () => {

            }
        })
    };


    const items: MenuProps['items'] = [
        {
            label: '循环运行',
            key: '1',
        },
    ];

    const menuProps = {
        items,
        onClick: handleMenuClick,
    };

    const askPermission = () => {

        return new Promise((resolve, reject) => {
            if (isFirefox()) {
                Ext.permissions.contains({ origins: ['<all_urls>'] }).then((permissionGranted: boolean) => {
                    if (!permissionGranted) {
                        Modal.confirm({
                            title: '授予权限',
                            content: `RPA IDE是一个用于自动化任务的开源工具。回放需要获得Firefox的许可才能“访问所有选项卡中的数据”。如果单击“确定”，RPA IDE将打开Firefox权限对话框，允许您提供此权限。是否继续?`,
                            okText: '继续',
                            cancelText: '取消',
                            onOk: () => {
                                Ext.permissions.request({ origins: ['<all_urls>'] }).then((result: boolean) => {
                                    console.log('permission result:>>', result);
                                    if (result) {
                                        resolve(true);
                                    } else {
                                        Ext.tabs.create({
                                            url: '',
                                            active: true,
                                        });
                                        resolve(false);
                                    }
                                });
                            },
                            onCancel: () => {
                                Ext.tabs.create({
                                    url: ' ',
                                    active: true,
                                });
                                resolve(false);
                            },
                        });
                    } else {
                        resolve(true);
                    }
                });
            } else {
                resolve(true);
            }
        });
    };

    const onToggleRecord = async () => {
        const tab: any = await getPlayTab()
        if (!/^(https?:|file:)/.test(tab.url)) {
            return message.error('Web录制仅适用于普通浏览器页面。');
        }

        if (status === APP_STATUS.RECORDER) {
            askBg('PANEL_STOP_RECORDING').then(() => {
                dispatch(stopRecording())
            })

        } else {
            const permissionResult = await askPermission();
            console.log('startRecording:>> askPermission complete: permissionResult:>>', permissionResult);
            if (!permissionResult) {
                return;
            }
            askBg('PANEL_START_RECORDING').then(() => {
                return askBg('PANEL_TRY_TO_RECORD_OPEN_COMMAND')
            }).then(() => {
                dispatch(startRecording())
            })
        }

    }


    const onClickSave = () => {
        dispatch(updateUI({ isSaving: true }))

        const existed = !!state.editor.editing.meta.src

        if (existed) {
            return dispatch(saveEditingAsExisted() as any).then(() => true)
        }

        let newName = ''
        Modal.confirm({
            title: "新建测试用例",
            content: <Input
                placeholder='测试用例名称'
                defaultValue='untitled'
                onChange={(e) => {
                    newName = e.target.value
                }} />,
            onOk: () => {
                return new Promise((resolve, reject) => {
                    dispatch(saveEditingAsNew(newName) as any).then(
                        () => {
                            message.success('保存成功!', 1.5)
                            resolve(true)
                        },
                        (e: any) => {
                            message.error(e.message, 1.5)
                            reject(e)
                        }
                    )
                })
            }
        })

        dispatch(updateUI({ isSaving: false }))
    }

    useEffect(() => {
        const beforeUnloadHandler = (event: any) => {
            if (hasUnsaved) {
                event.preventDefault();
                // Note: Chrome is showing the default message anyway
                const promptMessage = '您有未保存的更改。您想在离开应用程序之前保存吗？';
                event.returnValue = promptMessage;
                return promptMessage;
            }
        }
        window.addEventListener('beforeunload', beforeUnloadHandler);
        return () => {
            window.removeEventListener('beforeunload', beforeUnloadHandler);
        }
    }, [hasUnsaved])

    return (
        <div className="panel-header">
            <div className="panel-header-left">
                <span
                    title={macroName || 'Untitled'}
                    className={'test-case-name ' + hasUnsaved ? "unsaved" : ""}
                >
                    {macroName || 'Untitled'}
                </span>
            </div>
            <div className="panel-header-right">
                <Space>
                    {
                        playerStatus === PLAYER_STATUS.STOPPED && <Button
                            disabled={!hasUnsaved}
                            onClick={onClickSave}
                        >{macroId ? '保存' : '保存...'}</Button>
                    }
                    {
                        status === APP_STATUS.RECORDER && <Button
                            onClick={onToggleRecord}
                            style={{ color: '#ff0000' }}
                        >
                            <span>停止录制</span>
                        </Button>
                    }
                    {
                        playerStatus === PLAYER_STATUS.PLAYING && <Space>
                            <Button onClick={() => player.stop()}>
                                <span>终止</span>
                            </Button>
                            <Button onClick={() => player.pause()}>
                                <span>暂停</span>
                            </Button>
                        </Space>
                    }
                    {
                        playerStatus === PLAYER_STATUS.PAUSED && <Space>
                            {mode === PLAYER_MODE.TEST_CASE ? <Button onClick={() => player.resume(true)}>单步</Button> : null}
                            <Button onClick={() => player.stop()}>终止</Button>
                            <Button onClick={() => player.resume()}>继续</Button>
                        </Space>
                    }
                    {
                        playerStatus === PLAYER_STATUS.STOPPED && <Space>
                            <Button
                                onClick={onToggleRecord}
                            >
                                <span>录制</span>
                            </Button>
                            <Button
                                disabled={status !== APP_STATUS.NORMAL && status !== APP_STATUS.PLAYER}
                                type={"default"}
                                onClick={() => playCurrentMacro(true)}
                                className="play-button"
                            >
                                单步
                            </Button>
                            <Dropdown.Button menu={menuProps} onClick={handleButtonClick}>
                                运行
                            </Dropdown.Button>
                        </Space>
                    }
                </Space>
            </div>
        </div>
    )
}